﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Linq.Dynamic;
using System.Web.Mvc;
using SDT.Model;
using SDT.Lib.Common;
using SDT.Site.Properties;
using SDT.Site.ViewModels;
using SDT.Lib.Paging;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.Linq;
using SDT.Lib.Helpers;
using System.Web.Security;

namespace SDT.Site.Controllers
{
    public class ProductController : Controller
    {

        // GET: /Product/
        SDTDataContext db = new SDTDataContext();
        public ActionResult Index(int? id, int? priceid, int? catid, int? holidayid, int? eventid, int? sellid, int? page)
        {
            if (page == null) page = 1; ;
            var pageIndex = page.Value - 1;
            var pageSize = Convert.ToInt32(UserState.getUserStateFromRequest("product.PageSize", "pageSize", Settings.Default.ProductPageSize));
            string order = UserState.getUserStateFromRequest("product.order", "order", "ModDate").ToString();
            string orderDir = UserState.getUserStateFromRequest("product.orderDir", "orderDir", "desc").ToString();
            int orderID = Utils.ParseInt(UserState.getUserStateFromRequest("product.OrderByID", "ddlOrderBy", 0));
            var postYN = Request.HttpMethod == "POST" ? true : false;
            sellid = sellid.HasValue ? sellid.Value : 0;
            switch (orderID)
            {
                case 1:
                    order = "AddDate";
                    orderDir = "desc";
                    break;
                case 2:
                    order = "Name";
                    orderDir = "asc";
                    break;
                case 3:
                    order = "UnitPrice";
                    orderDir = "asc";
                    break;
                default:
                    order = "ModDate";
                    orderDir = "desc";
                    break;
            }

            ViewData["orderDir"] = orderDir;
            ViewData["order"] = order;
            ProductSearchModels p = new ProductSearchModels();
            p.HolidayID = holidayid.HasValue ? holidayid.Value : 0;
            p.CategoryID = catid.HasValue ? catid.Value : 0;
            p.EventID = eventid.HasValue ? eventid.Value : 0;
            p.PriceID = priceid.HasValue ? priceid.Value : 0;
            p.TypeID = id.HasValue ? id.Value : 0;
            p.OrderID = orderID;
            p.SellID = sellid;
            p.Keyword = Request["key"] != null ? Request["key"] : string.Empty;
            //sellid = 1 newyn=true, 2: hotyn, 3: saleyn, 4: promoyn
            p.Products = ProductManager.GetList(p.TypeID, p.CategoryID, p.HolidayID, p.PriceID, p.EventID,
                0, p.Keyword, sellid == 2 ? 1 : 0, 1, sellid == 3 ? 1 : 0, sellid == 1 ? 1 : 0, sellid == 4 ? 1 : 0, 2,
                order, orderDir, pageIndex, pageSize);

            p.Times = Utils.StringToDictionaryIntString(Settings.Default.SearchByTime, ";");
            p.OrderBy = Utils.StringToDictionaryIntString(Settings.Default.ProductOrderBy, ",");
            p.Sells = Utils.StringToDictionaryIntString(Settings.Default.ProductSell, ",");

            p.ImageUrl = Settings.Default.SiteRootUrl + Settings.Default.ProductRootUrl;
            p.ImagePath = Settings.Default.SiteRootPath + Settings.Default.ProductRootPath;


            p.Categories = db.ProductCategories.Where(e => e.ActiveYN == true).OrderBy(e => e.Priority).ToList();
            p.ProductHolidays = db.ProductHolidays.OrderBy(e => e.Priority).ToList();
            p.ConvertPrices = db.ConvertPrices.ToList();
            p.ProductTypes = db.ProductTypes.ToList();

            p.ProductType = db.ProductTypes.Where(e => e.ID == p.TypeID).SingleOrDefault();
            p.Category = db.ProductCategories.Where(e => e.ID == p.CategoryID).SingleOrDefault();
            p.ProductHoliday = db.ProductHolidays.Where(e => e.ID == p.HolidayID).SingleOrDefault();
            p.ConvertPrice = db.ConvertPrices.Where(e => e.ID == p.PriceID).SingleOrDefault();
            p.Event = db.Events.Where(e => e.ID == p.EventID).SingleOrDefault();

            if (p.ProductType != null) {
                p.ProductTypes.Remove(p.ProductType);
                p.ProductTypes.Insert(0, p.ProductType);
            }
            if (p.Category != null)
            {
                p.Categories.Remove(p.Category);
                p.Categories.Insert(0, p.Category);
            }
            if (p.ProductHoliday != null)
            {
                p.ProductHolidays.Remove(p.ProductHoliday);
                p.ProductHolidays.Insert(0, p.ProductHoliday);
            }
            return View(p);
        }
        public ActionResult ListTag(int? id, int? page)
        {
            if (page == null) page = 1; ;
            var pageIndex = page.Value - 1;
            var pageSize = Convert.ToInt32(UserState.getUserStateFromRequest("product.PageSize", "pageSize", Settings.Default.ProductPageSize));
            string order = UserState.getUserStateFromRequest("product.order", "order", "ModDate").ToString();
            string orderDir = UserState.getUserStateFromRequest("product.orderDir", "orderDir", "desc").ToString();
            int orderID = Utils.ParseInt(UserState.getUserStateFromRequest("product.OrderByID", "ddlOrderBy", 0));
            switch (orderID)
            {
                case 1:
                    order = "AddDate";
                    orderDir = "desc";
                    break;
                case 2:
                    order = "Name";
                    orderDir = "asc";
                    break;
                case 3:
                    order = "UnitPrice";
                    orderDir = "asc";
                    break;
                default:
                    order = "ModDate";
                    orderDir = "desc";
                    break;
            }

            ViewData["orderDir"] = orderDir;
            ViewData["order"] = order;
            ProductSearchModels p = new ProductSearchModels();
            p.HolidayID = 0;
            p.CategoryID = 0;
            p.EventID = 0;
            p.PriceID = 0;
            p.TypeID = 0;
            p.OrderID = orderID;
            p.SellID = 0;
            p.Keyword = Request["key"] != null ? Request["key"] : string.Empty;
            var tagid = id.HasValue ? id.Value : 0;
            //sellid = 1 newyn=true, 2: hotyn, 3: saleyn, 4: promoyn
            p.Products = ProductManager.GetListInTag(p.TypeID, p.CategoryID, p.HolidayID, p.PriceID, p.EventID,
                0, tagid, p.Keyword, 0, 1, 0, 0, 0,2,
                order, orderDir, pageIndex, pageSize);

            p.OrderBy = Utils.StringToDictionaryIntString(Settings.Default.ProductOrderBy, ",");
            p.Sells = Utils.StringToDictionaryIntString(Settings.Default.ProductSell, ",");

            p.ImageUrl = Settings.Default.SiteRootUrl + Settings.Default.ProductRootUrl;
            p.ImagePath = Settings.Default.SiteRootPath + Settings.Default.ProductRootPath;


            p.Categories = db.ProductCategories.Where(e => e.ActiveYN == true).OrderBy(e => e.Priority).ToList();
            p.ProductHolidays = db.ProductHolidays.OrderBy(e => e.Priority).ToList();
            p.ConvertPrices = db.ConvertPrices.ToList();
            p.ProductTypes = db.ProductTypes.ToList();

            p.Tag = id.HasValue ? db.Tags.Where(e => e.ID == id.Value).SingleOrDefault() : null;
            return View(p);
        }
        public ActionResult Details(int id)
        {
            ProductDetailsModels p = new ProductDetailsModels();
            p.Product = db.Products.Where(e => e.ID == id).SingleOrDefault();
            string subPath = string.Format("{0}\\{1}\\{2}\\", p.Product.AddDate.Value.Year, p.Product.AddDate.Value.Month, p.Product.AddDate.Value.Day);
            string subUrl = string.Format("{0}/{1}/{2}/", p.Product.AddDate.Value.Year, p.Product.AddDate.Value.Month, p.Product.AddDate.Value.Day);

            p.ImageUrl = Settings.Default.SiteRootUrl + Settings.Default.ProductRootUrl + subUrl;
            p.ImagePath = Settings.Default.SiteRootPath + Settings.Default.ProductRootPath + subPath;
            p.LogoPath = Settings.Default.SiteRootPath + Globals.DefaultLogoPath;


            p.ProductSearch = new ProductSearchModels();
            p.ProductSearch.Times = Utils.StringToDictionaryIntString(Settings.Default.SearchByTime, ";");
            p.ProductSearch.OrderBy = Utils.StringToDictionaryIntString(Settings.Default.ProductOrderBy, ",");
            p.ProductSearch.Sells = Utils.StringToDictionaryIntString(Settings.Default.ProductSell, ",");
            p.ProductSearch.Categories = db.ProductCategories.Where(e => e.ActiveYN == true).OrderBy(e => e.Priority).ToList();

            p.ProductSearch.ConvertPrices = db.ConvertPrices.ToList();
            p.ProductSearch.ProductHolidays = db.ProductHolidays.OrderBy(e => e.Priority).ToList();
            p.ProductSearch.ProductTypes = db.ProductTypes.ToList();

            p.ProductSearch.Category = p.Product.ProductCategory;
            if (p.ProductSearch.Category != null)
            {
                p.ProductSearch.Categories.Remove(p.ProductSearch.Category);
                p.ProductSearch.Categories.Insert(0, p.ProductSearch.Category);
            }
            p.ProductSearch.ConvertPrice = null;

            p.ProductSearch.CategoryID = p.Product.CatID;

            p.ProductSearch.PriceID = 0;
            p.ProductSearch.TimeID = 0;
            p.ProductSearch.SellID = 0;
            p.ProductSearch.PathTitle = p.Product.Name;
            p.Keyword = string.Empty;
            //luot xem
            var pr = db.Products.SingleOrDefault(d => d.ID == id);
            pr.nViews++;
            db.SubmitChanges();

            return View(p);
        }
        [HttpPost()]
        public ActionResult Search(ProductSearchModels p)
        {

            p.HolidayID = Utils.ParseInt(Request["ddlHoliday"], 0); ;
            p.CategoryID = Utils.ParseInt(Request["ddlCategory"], 0);
            p.PriceID = Utils.ParseInt(Request["ddlPrice"], 0);
            p.TimeID = Utils.ParseInt(Request["ddlTime"], 0);
            p.TypeID = Utils.ParseInt(Request["ddlType"], 0);
            p.Keyword = Request["txtKeyword"] != null ? Request["txtKeyword"] : string.Empty;

            var path = string.Format("index/{0}/{1}/{2}/{3}/{4}",
                   p.TypeID.HasValue ? p.TypeID.Value : 0,
                   p.PriceID.HasValue ? p.PriceID.Value : 0,
                   p.CategoryID.HasValue ? p.CategoryID.Value : 0,
                   p.HolidayID.HasValue ? p.HolidayID.Value : 0,
                   p.EventID.HasValue ? p.EventID.Value : 0
                  );
            path = TextHelper.ToUrlShort(path);
            if (p.Keyword != null && p.Keyword != string.Empty) path = path + "?key=" + p.Keyword;
            return RedirectToAction(path, "product");
        }
        public ActionResult List(int id, int? page)
        {
            if (page == null) page = 1; ;
            var pageIndex = page.Value - 1;
            var pageSize = Convert.ToInt32(UserState.getUserStateFromRequest("productlist.PageSize", "pageSize", Settings.Default.ProductPageSize));
            string order = UserState.getUserStateFromRequest("productlist.order", "order", "ID").ToString();
            string orderDir = UserState.getUserStateFromRequest("productlist.orderDir", "orderDir", "desc").ToString();
            ProductSearchModels p = new ProductSearchModels();
            var cp = db.Products.Where(e => e.ID == id).SingleOrDefault();
            p.HolidayID = 0;
            p.CategoryID = cp.CatID;
            p.EventID = 0;
            p.PriceID = 0;
            p.TimeID = 0;
            p.TypeID = 0;

            p.Keyword = string.Empty;
            p.Products = ProductManager.GetList(p.TypeID, p.CategoryID, p.HolidayID,
                p.PriceID, p.EventID, 0, p.Keyword, 0, 1, 0, 0, 0, 2,
                 order, orderDir, pageIndex, Utils.ParseInt(Settings.Default.ProductPageSize));

            p.PathTitle = "";
            p.ImageUrl = Settings.Default.SiteRootUrl + Settings.Default.ProductRootUrl;
            p.ImagePath = Settings.Default.SiteRootPath + Settings.Default.ProductRootPath;

            p.ProductType = p.TypeID > 0 ? db.ProductTypes.Where(e => e.ID == p.TypeID).SingleOrDefault() : null;

            p.Categories = db.ProductCategories.Where(e => e.ActiveYN == true).OrderBy(e => e.Priority).ToList();
            p.ProductHolidays = db.ProductHolidays.OrderBy(e => e.Priority).ToList();
            p.ConvertPrices = db.ConvertPrices.ToList();
            p.ProductTypes = db.ProductTypes.ToList();

            p.ProductType = db.ProductTypes.Where(e => e.ID == p.TypeID).SingleOrDefault();
            p.Category = db.ProductCategories.Where(e => e.ID == p.CategoryID).SingleOrDefault();
            p.ProductHoliday = db.ProductHolidays.Where(e => e.ID == p.HolidayID).SingleOrDefault();
            p.ConvertPrice = db.ConvertPrices.Where(e => e.ID == p.PriceID).SingleOrDefault();
            return View(p);
        }
        [ChildActionOnly]
        public ActionResult Lasted(int typeid, int? catid, int? holidayid, int number,
            int hotYN, int newYN, int saleYN, int promoYN, string order, string orderDir, string title, string viewName)
        {
            var p = new ProductListModels();
            var db = new SDTDataContext();
            var l = ProductManager.GetList(typeid, catid, holidayid, 0, 0, hotYN, 1, saleYN, newYN, promoYN, 2, string.Empty, order, orderDir, number);
            p.Products = l;
            p.ImageUrl = Settings.Default.SiteRootUrl + Settings.Default.ProductRootUrl;
            p.ImagePath = Settings.Default.SiteRootPath + Settings.Default.ProductRootPath;
            ViewData["Title"] = title;
            return PartialView(viewName, p);
        }

        [ChildActionOnly]
        public ActionResult SearchHome(int typeid)
        {
            ProductSearchModels p = new ProductSearchModels();
            p.Categories = db.ProductCategories.Where(e => e.ActiveYN == true).OrderBy(e => e.Priority).ToList();
            p.ProductHolidays = db.ProductHolidays.OrderBy(e => e.Priority).ToList();
            p.ConvertPrices = db.ConvertPrices.ToList();
            p.ProductTypes = db.ProductTypes.ToList();
            return View(p);
        }
        [ChildActionOnly]
        public ActionResult GetHome(string viewName)
        {
            ProductSearchModels p = new ProductSearchModels();
            p.Categories = db.ProductCategories.Where(e => e.ActiveYN == true).OrderBy(e => e.Priority).ToList();
            p.ProductHolidays = db.ProductHolidays.OrderBy(e => e.Priority).ToList();
            p.ConvertPrices = db.ConvertPrices.ToList();
            p.ProductTypes = db.ProductTypes.ToList();
            return PartialView(viewName, p);
        }
        [ChildActionOnly]
        public ActionResult OtherItems(int id, int number, string title, string viewName)
        {
            var a = new ProductListModels();
            var current_product = db.Products.Where(e => e.ID == id).SingleOrDefault();
            var l = ProductManager.GetOtherList(id, 0, current_product.CatID, 0, 0,
                0, 0, 1, 0, 0, 0,2, string.Empty, "ID", "desc", number);
            ViewData["Title"] = title;
            a.ImageUrl = Settings.Default.SiteRootUrl + Settings.Default.ProductRootUrl;
            a.ImagePath = Settings.Default.SiteRootPath + Settings.Default.ProductRootPath;
            a.Products = l;
            return PartialView(viewName, a);
        }
        [ChildActionOnly]
        public ActionResult GetCart(string title, string viewName)
        {
            var cart = Session[SDT.Lib.Common.Messages.Cart] != null ?
                (SDT.Site.ViewModels.CartViewModels)Session[SDT.Lib.Common.Messages.Cart] :
                new SDT.Site.ViewModels.CartViewModels();
            cart.ImageUrl = Settings.Default.SiteRootUrl + Settings.Default.ProductRootUrl;
            cart.ImagePath = Settings.Default.SiteRootPath + Settings.Default.ProductRootPath;
            ViewData["Title"] = title;
            cart.ImageUrl = Settings.Default.SiteRootUrl + Settings.Default.ProductRootUrl;
            cart.ImagePath = Settings.Default.SiteRootPath + Settings.Default.ProductRootPath;
            return PartialView(viewName, cart);
        }
        [ChildActionOnly]
        public ActionResult GetTags(int typeid, int? catid, int? holidayid, int? eventid, int number,
             string title, string order, string orderDir, string viewName)
        {
            var p = new ProductTagModels();
            var db = new SDTDataContext();
            var l = ProductManager.GetTags(typeid, catid, holidayid, eventid, order, orderDir, number);
            p.Tags = l;
            ViewData["Title"] = title;
            return PartialView(viewName, p);
        }
        [ChildActionOnly]
        public ActionResult LatestComments(int id, int number)
        {
            var latestC = new List<Comment>();
            try
            {
                latestC = ProductManager.GetComments(id, true, number).ToList();
            }
            catch (Exception exp)
            {
                ErrorLog.WriteLog(exp);
            }
            return PartialView(latestC);
        }
        [ChildActionOnly]
        public ActionResult Comment(int id)
        {
            var c = new Comment();
            return PartialView(c);
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Comment(int id, Comment c)
        {
            try
            {
                UpdateModel(c);
                if (c.Title != null && c.Title != string.Empty)
                {
                    c.CommentDate = DateTime.Now;
                    c.PublishYN = false;
                    db.Comments.InsertOnSubmit(c);
                    db.SubmitChanges();
                    var map = new CommentsInProduct();
                    map.CommentID = c.ID;
                    map.ProductID = id;
                    db.CommentsInProducts.InsertOnSubmit(map);
                    db.SubmitChanges();
                }
                return RedirectToAction("Details", new { id = id });
            }
            catch (Exception exp)
            {
                return RedirectToAction("Details", new { id = id });
            }
        }
        #region Binhlv/ GetConvertPrice
        private ConvertPrice GetConvertPrice(decimal TotalPrice)
        {
            try
            {
                if (TotalPrice < 0) throw new NotSupportedException();
                var maxArea = db.ConvertPrices

                    .OrderByDescending(e => e.MaxValue)
                    .FirstOrDefault();
                if (TotalPrice > maxArea.MaxValue)
                {
                    return maxArea;
                }
                var CurrentConvertPrice = db.ConvertPrices
                                        .Where(c => c.MinValue < TotalPrice && c.MaxValue >= TotalPrice) // Modified by Vietlv test vaule of boundaris (">" --> ">=")
                                        .FirstOrDefault();
                return CurrentConvertPrice;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
    }
}
